#!/usr/bin/env python3
#coding: utf-8

import re
import subprocess
from execute_log import ExecuteLog

def decode_command_result(command_result) -> str:
    result = command_result.decode('gbk').encode('utf-8').decode()
    return re.sub(r'\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))', '', result)

class ExecuteCommand:
    def execute(self, command: list[str], logger: ExecuteLog, timeout: int = 30, cwd: None | str = None) -> [bool, str]:
        cmd_str = ''.join(command)
        logger.info(f'execute command: {cmd_str}')
        try:
            result = subprocess.run(cmd_str,
                                    check=True,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    timeout=timeout)
            if result.returncode != 0:
                err = result.stderr
                logger.error(f'An error was encountered while executing command: {err}')
                return [False, f'{err}']
            else:
                out = decode_command_result(result.stdout)
                return [True, f'{out}']
        except subprocess.CalledProcessError as exception:
            logger.error(f'An error was encountered while executing command: {exception.stderr}')
            return [False, f'{exception.stderr}']
        except Exception as exception:
            logger.error(f'An unknown error was encountered while executing command: {exception}')
            return [False, '{exception}']
